package collector.module.listener;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import collector.core.CollectConstants;
import collector.task.JobStateVO;


public class RmiRemote_01_JobListener implements JobListener {

	private static Logger _log = LoggerFactory.getLogger(RmiRemote_01_JobListener.class);
	private static final String _LogPrefixStr = CollectConstants.LOGGER_MODULE_NAME_RJLC + CollectConstants.LOGGER_MODULE_NAME_AFTFIX;

	public static final String LISTENER_NAME = "dummyRmiRemote_01_JobListenerName";

	//@Override
	public String getName() {
		return LISTENER_NAME; //must return a name
	}

	// Run this if job is about to be executed.
	//@Override
	public void jobToBeExecuted(JobExecutionContext context) {

		String jobName = context.getJobDetail().getKey().toString();
		
	    	_log.info(_LogPrefixStr + "----- jobToBeExecuted ~~~" + " Job : " + jobName + " is going to start...");
	    	logListenerJobInfo(context, "Current");

	}

	// No idea when will run this?
	//@Override
	public void jobExecutionVetoed(JobExecutionContext context) {
	    	_log.info(_LogPrefixStr + "----- jobExecutionVetoed ~~~");
	}

	//Run this after job has been executed
	//@Override
	public void jobWasExecuted(JobExecutionContext context,
			JobExecutionException jobException) {
		String jobName = context.getJobDetail().getKey().toString();
	    	_log.info(_LogPrefixStr + "----- jobWasExecuted ~~~" + " Job : " + jobName + " is finished...");
	    	logListenerJobInfo(context, "Result");

		if (jobException != null && !jobException.getMessage().equals("")) {
		    	_log.error(_LogPrefixStr + "Exception thrown by: " + jobName + " Exception: " + jobException.getMessage(), jobException);
		}

	}

	private void logListenerJobInfo(JobExecutionContext context, String prefixMsg) {
		try {
		    	_log.debug(_LogPrefixStr + prefixMsg + " RecCount=" + context.getJobDetail().getJobDataMap().getIntValue(CollectConstants.EXECUTION_RECCOUNT));
		    	_log.debug(_LogPrefixStr + prefixMsg + " PreJobState=" + context.getJobDetail().getJobDataMap().getIntValue(CollectConstants.EXECUTION_PREJOBSTATE));
		    	_log.debug(_LogPrefixStr + prefixMsg + " JobStateVo :: " + (JobStateVO)context.getJobDetail().getJobDataMap().get(CollectConstants.EXECUTION_JOBSTATEVO));
		    	_log.debug(_LogPrefixStr + prefixMsg + " msg=" + context.getJobDetail().getJobDataMap().getString(CollectConstants.EXECUTION_MESSAGE));
		} catch(Exception e) {
		    _log.error(_LogPrefixStr + "Exception happen by: " + context.getJobDetail().getKey().toString() + " Exception: " + e.getMessage(), e);
		}

		return;
	}
}